<template>
  <div class="app-container">
    <el-form ref="noticedemandapprovalRef" :model="formData" :rules="rules" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="立案号" prop="caseId">
            <el-select
              v-model="formData.caseId"
              placeholder="请选择立案号"
              :disabled="disabled"
              clearable
              @change="handleCase">
              <el-option v-for="item in numberList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="当事人名称" prop="partyName">
            <el-input v-model="formData.partyName" disabled placeholder="请输入当事人名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="讨论时间" prop="daterangeApplyTime">
            <el-date-picker
              clearable
              v-model="daterangeApplyTime"
              type="datetimerange"
              value-format="YYYY-MM-DD HH:mm:ss"
              :disabled="disabled"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="讨论地点" prop="discussionPlace">
            <el-input v-model="formData.discussionPlace" :disabled="disabled" placeholder="请输入讨论地点" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="主持人" prop="hostName" class="long-label">
            <el-input v-model="formData.hostName" :disabled="disabled" placeholder="请输入主持人姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="职务" prop="hostPosition" class="long-label">
            <el-input v-model="formData.hostPosition" :disabled="disabled" placeholder="请输入主持人职务" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="记录人" prop="recorderName" class="long-label">
            <el-input v-model="formData.recorderName" :disabled="disabled" placeholder="请输入记录人姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="职务" prop="recorderPosition" class="long-label">
            <el-input v-model="formData.recorderPosition" :disabled="disabled" placeholder="请输入记录人职务" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <div class="form-title-text-two" style="margin-bottom: 20px">出席人员姓名及职务</div>
        </el-col>
        <template v-for="(item, index) in formData.tGroupDiscussionPresentPersonList" :key="item.id">
          <el-col :span="8">
            <el-form-item label="姓名" :prop="`tGroupDiscussionPresentPersonList[${index}].name`" :rules="rules.name">
              <el-input v-model="item.name" :disabled="disabled" placeholder="请输入出席人员姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="职务"
              :prop="`tGroupDiscussionPresentPersonList[${index}].position`"
              :rules="rules.position">
              <el-input v-model="item.position" :disabled="disabled" placeholder="请输入出席人员职务" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-top: 6px">
            <el-button
              v-if="index === formData.tGroupDiscussionPresentPersonList.length - 1"
              type="primary"
              link
              :disabled="disabled"
              icon="CirclePlus"
              @click="handleAddPresent" />
            <el-button
              v-if="formData.tGroupDiscussionPresentPersonList.length > 1"
              type="danger"
              link
              :disabled="disabled"
              icon="delete"
              @click="handleRemovePresent(item)" />
          </el-col>
        </template>

        <el-col :span="24">
          <div class="form-title-text-two" style="margin-bottom: 20px">缺席人员姓名及职务</div>
        </el-col>
        <template v-for="(item, index) in formData.tGroupDiscussionAbsentPersonList" :key="item.id">
          <el-col :span="8">
            <el-form-item label="姓名" :prop="`tGroupDiscussionAbsentPersonList[${index}].name`" :rules="rules.name">
              <el-input v-model="item.name" :disabled="disabled" placeholder="请输入缺席人员姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="职务"
              :prop="`tGroupDiscussionAbsentPersonList[${index}].position`"
              :rules="rules.position">
              <el-input v-model="item.position" :disabled="disabled" placeholder="请输入缺席人员职务" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-top: 6px">
            <el-button
              v-if="index === formData.tGroupDiscussionAbsentPersonList.length - 1"
              type="primary"
              link
              :disabled="disabled"
              icon="CirclePlus"
              @click="handleAddAbsent" />
            <el-button
              v-if="formData.tGroupDiscussionAbsentPersonList.length > 1"
              type="danger"
              link
              :disabled="disabled"
              icon="delete"
              @click="handleRemoveAbsent(item)" />
          </el-col>
        </template>

        <el-col :span="24">
          <div class="form-title-text-two" style="margin-bottom: 20px">列席人员姓名及职务</div>
        </el-col>
        <template v-for="(item, index) in formData.tGroupDiscussionAttendeePersonList" :key="item.id">
          <el-col :span="8">
            <el-form-item label="姓名" :prop="`tGroupDiscussionAttendeePersonList[${index}].name`" :rules="rules.name">
              <el-input v-model="item.name" :disabled="disabled" placeholder="请输入列席人员姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="职务"
              :prop="`tGroupDiscussionAttendeePersonList[${index}].position`"
              :rules="rules.position">
              <el-input v-model="item.position" :disabled="disabled" placeholder="请输入列席人员职务" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-top: 6px">
            <el-button
              v-if="index === formData.tGroupDiscussionAttendeePersonList.length - 1"
              type="primary"
              link
              :disabled="disabled"
              icon="CirclePlus"
              @click="handleAddAttend" />
            <el-button
              v-if="formData.tGroupDiscussionAttendeePersonList.length > 1"
              type="danger"
              link
              :disabled="disabled"
              icon="delete"
              @click="handleRemoveAttend(item)" />
          </el-col>
        </template>
        <CaseSituation
          ref="caseSituationRef"
          v-model="formData"
          :disabled="disabled"
          :show="'案情说明, 证据证明, 违反条例, 陈述申辩, 处理依据'"
          title="案件承办人介绍案情和处罚意见："
          :caseIsEdit="true"
          :stateIsEdit="true"
          :isEdit="true"
          :violationIsEdit="true" />
        <el-col :span="24">
          <div class="form-title-text-two" style="margin-bottom: 20px">执法队法制科负责人介绍审核意见</div>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="legalHandlerOpinion">
            <SmartTextInput
              v-model="formData.legalHandlerOpinion"
              type="textarea"
              :disabled="disabled"
              :rows="4"
              placeholder="请输入执法队法制科负责人介绍审核意见"
              :min-length="2"
              :max-suggestions="5"
              contentType="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <div class="form-title-text-two" style="margin-bottom: 20px">法宣科负责人介绍审核意见</div>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="legalInstitutionsOpinion">
            <SmartTextInput
              v-model="formData.legalInstitutionsOpinion"
              type="textarea"
              :disabled="disabled"
              :rows="4"
              placeholder="请输入法宣科负责人介绍审核意见"
              :min-length="2"
              :max-suggestions="5"
              contentType="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <div class="form-title-text-two" style="margin-bottom: 20px">出席人员分别发表意见</div>
        </el-col>
        <template v-for="(item, index) in formData.tGroupDiscussionPresentPersonList" :key="item.id">
          <el-col :span="8">
            <el-form-item label="姓名" :prop="`tGroupDiscussionPresentPersonList[${index}].name`" :rules="rules.name">
              <el-input v-model="item.name" disabled placeholder="请输入出席人员姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :prop="`tGroupDiscussionPresentPersonList[${index}].opinion`" :rules="rules.opinion">
              <el-input
                v-model="item.opinion"
                type="textarea"
                :rows="3"
                :disabled="disabled"
                placeholder="请输入意见" />
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="24">
          <div class="form-title-text-two" style="margin-bottom: 20px">主要领导发表结论性意见</div>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="leaderOption">
            <el-input
              v-model="formData.leaderOption"
              type="textarea"
              :rows="3"
              :disabled="disabled"
              placeholder="请输入主要领导发表结论性意见" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, watch } from 'vue'
import {
  getGroupDiscussion,
  addGroupDiscussion,
  updateGroupDiscussion,
  getCaseList,
  getContent,
  previewPdf,
} from '@/api/caseHandling/groupDiscussion.js'
import { registrationcaseDetail } from '@/api/filingReview/register'
import { ElMessage } from 'element-plus'
import locationSelect from '@/components/locationSelect/index.vue'
import CaseSituation from '@/components/CaseSituation/index.vue'
import SmartTextInput from '@/components/SmartTextInput/index.vue'

const { proxy } = getCurrentInstance()

// Props
const props = defineProps({
  id: {
    type: [String, Number],
    default: null,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
})

// Emits
const emit = defineEmits(['handleSubmit'])

// Form data
const formData = ref({
  id: null,
  caseId: null,
  caseNo: null,
  partyName: null,
  discussionPlace: null,
  caseDesc: null,
  evidenceDesc: null,
  violationRegulations: null,
  statementDefense: null,
  handlingBasis: null,
  legalHandlerOpinion: null,
  legalInstitutionsOpinion: null,
  tGroupDiscussionPresentPersonList: [{ id: '1', name: '', position: '', opinion: '' }],
  tGroupDiscussionAbsentPersonList: [{ id: '1', name: '', position: '' }],
  tGroupDiscussionAttendeePersonList: [{ id: '1', name: '', position: '' }],
  leaderOption: null,
})
const daterangeApplyTime = ref([])
const validateTime = (rule, value, callback) => {
  if (!daterangeApplyTime.value || daterangeApplyTime.value.length !== 2) {
    callback(new Error('请选择讨论时间'))
  } else {
    // 验证是否是同一天
    const startDate = new Date(daterangeApplyTime.value[0])
    const endDate = new Date(daterangeApplyTime.value[1])

    const isSameDay =
      startDate.getFullYear() === endDate.getFullYear() &&
      startDate.getMonth() === endDate.getMonth() &&
      startDate.getDate() === endDate.getDate()

    if (!isSameDay) {
      callback(new Error('讨论时间不能跨天'))
    } else if (startDate.getTime() >= endDate.getTime()) {
      callback(new Error('结束时间必须大于开始时间'))
    } else {
      callback()
    }
  }
}
// Form validation rules
const rules = {
  caseNo: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
  partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
  daterangeApplyTime: [{ required: true, validator: validateTime, trigger: ['blur', 'change'] }],
  hostName: [{ required: true, message: '主持人姓名不能为空', trigger: ['blur', 'change'] }],
  hostPosition: [{ required: true, message: '主持人职务不能为空', trigger: ['blur', 'change'] }],
  recorderName: [{ required: true, message: '记录人姓名不能为空', trigger: ['blur', 'change'] }],
  recorderPosition: [{ required: true, message: '记录人职务不能为空', trigger: ['blur', 'change'] }],
  caseDesc: [{ required: true, message: '请输入案情说明', trigger: ['blur', 'change'] }],
  evidenceDesc: [{ required: true, message: '请输入证据证明', trigger: ['blur', 'change'] }],
  violationRegulations: [{ required: true, message: '请输入违反条例', trigger: ['blur', 'change'] }],
  statementDefense: [{ required: true, message: '请输入陈述申辩', trigger: ['blur', 'change'] }],
  handlingBasis: [{ required: true, message: '请输入处理依据', trigger: ['blur', 'change'] }],
  caseId: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
  discussionPlace: [{ required: true, message: '请输入讨论地点', trigger: ['blur', 'change'] }],
  legalHandlerOpinion: [
    { required: true, message: '请输入执法队法制科负责人介绍审核意见', trigger: ['blur', 'change'] },
  ],
  legalInstitutionsOpinion: [
    { required: true, message: '请输入法宣科负责人介绍审核意见', trigger: ['blur', 'change'] },
  ],
  name: [{ required: true, message: '姓名不能为空', trigger: ['blur', 'change'] }],
  position: [{ required: true, message: '职务不能为空', trigger: ['blur', 'change'] }],
  opinion: [{ required: true, message: '意见不能为空', trigger: ['blur', 'change'] }],
  leaderOption: [{ required: true, message: '请输入主要领导发表结论性意见', trigger: ['blur', 'change'] }],
}

// Refs
const noticedemandapprovalRef = ref()

// Methods
const reset = () => {
  formData.value = {
    id: null,
    caseId: null,
    caseNo: null,
    partyName: null,
    discussionPlace: null,
    caseDesc: null,
    evidenceDesc: null,
    violationRegulations: null,
    statementDefense: null,
    handlingBasis: null,
    legalHandlerOpinion: null,
    legalInstitutionsOpinion: null,
    tGroupDiscussionPresentPersonList: [{ id: '1', name: '', position: '', opinion: '同意综合执法大队处罚建议' }],
    tGroupDiscussionAbsentPersonList: [{ id: '1', name: '', position: '' }],
    tGroupDiscussionAttendeePersonList: [{ id: '1', name: '', position: '' }],
    leaderOption: null,
  }
  proxy.resetForm('noticedemandapprovalRef')
  daterangeApplyTime.value = []
}
// 添加出席人员
const handleAddPresent = () => {
  formData.value.tGroupDiscussionPresentPersonList.push({
    id: Date.now().toString(),
    name: '',
    position: '',
    opinion: '同意综合执法大队处罚建议',
  })
}
// 移除出席人员
const handleRemovePresent = item => {
  formData.value.tGroupDiscussionPresentPersonList = formData.value.tGroupDiscussionPresentPersonList.filter(
    i => i.id !== item.id
  )
}

// 添加缺席人员
const handleAddAbsent = () => {
  formData.value.tGroupDiscussionAbsentPersonList.push({
    id: Date.now().toString(),
    name: '',
    position: '',
  })
}
// 移除缺席人员
const handleRemoveAbsent = item => {
  formData.value.tGroupDiscussionAbsentPersonList = formData.value.tGroupDiscussionAbsentPersonList.filter(
    i => i.id !== item.id
  )
}

// 添加列席人员
const handleAddAttend = () => {
  formData.value.tGroupDiscussionAttendeePersonList.push({
    id: Date.now().toString(),
    name: '',
    position: '',
  })
}
// 移除列席人员
const handleRemoveAttend = item => {
  formData.value.tGroupDiscussionAttendeePersonList = formData.value.tGroupDiscussionAttendeePersonList.filter(
    i => i.id !== item.id
  )
}

// Get detail data
const getDetail = async id => {
  reset()
  if (id) {
    try {
      const res = await getGroupDiscussion(id)
      formData.value = res.data
      daterangeApplyTime.value = [res.data.discussionStartTime, res.data.discussionEndTime]
    } catch (error) {
      console.error('获取详情失败:', error)
    }
  }
}

const handleCase = async val => {
  return new Promise(async (resolve, reject) => {
    if (!val) {
      formData.value.caseNo = ''
      formData.value.partyName = ''
      formData.value.partyId = ''
      formData.value.leaderOption = ''
      formData.value.caseDesc = ''
      formData.value.evidenceDesc = ''
      formData.value.violationRegulations = ''
      formData.value.statementDefense = ''
      formData.value.handlingBasis = ''
      formData.value.legalHandlerOpinion = ''
      formData.value.legalInstitutionsOpinion = ''
      return
    }
    const res = await registrationcaseDetail(val)
    const { partyName, partyId } = res.data
    formData.value.caseNo = res.data.caseNo
    formData.value.partyName = partyName
    formData.value.partyId = partyId
    const res2 = await getContent(val)
    formData.value.caseDesc = res2.data.caseDesc
    formData.value.evidenceDesc = res2.data.evidenceDesc
    formData.value.violationRegulations = res2.data.violationRegulations
    formData.value.statementDefense = res2.data.statementDefense
    formData.value.handlingBasis = res2.data.handlingBasis
    formData.value.legalHandlerOpinion = res2.data.legalHandlerOpinion
    formData.value.legalInstitutionsOpinion = res2.data.legalInstitutionsOpinion
    nextTick(() => {
      caseSituationRef.value.pullCaseDescOnly()
    })
    resolve()
  })
}

const handlePreview = () => {
  return new Promise(resolve => {
    submitForm(true)
      .then(async params => {
        previewPdf(params)
          .then(res => {
            if (!!res.msg) {
              window.open(res.msg)
              resolve()
            } else {
              ElMessage.warning('预览文件不存在')
              resolve()
            }
          })
          .catch(() => {
            ElMessage.warning('预览文件不存在')
            resolve()
          })
      })
      .catch(() => {
        ElMessage.warning('请先完善表单信息')
        resolve()
      })
  })
}

// Submit form
const caseSituationRef = ref(null)
const submitForm = (isPreview = false) => {
  return new Promise((resolve, reject) => {
    noticedemandapprovalRef.value
      .validate()
      .then(async () => {
        let num = 0
        caseSituationRef.value.reasonSegments.forEach(item => {
          if (item.type === 'input' && !item.value) {
            num += 1
          }
        })
        if (num > 0) {
          ElMessage.error('请将催告理由填写完整')
          return false
        }
        num = 0
        caseSituationRef.value.handlerOpinionSegments.forEach(item => {
          if (item.type === 'input' && !item.value) {
            num += 1
          }
        })
        if (num > 0) {
          ElMessage.error('请将承办人意见填写完整')
          return false
        }
        const params = JSON.parse(JSON.stringify(formData.value))
        if (daterangeApplyTime.value.length === 2) {
          params.discussionStartTime = daterangeApplyTime.value[0]
          params.discussionEndTime = daterangeApplyTime.value[1]
        } else {
          params.discussionStartTime = null
          params.discussionEndTime = null
        }
        if (isPreview === true) {
          resolve(params)
          return
        }
        let result
        if (params.id) {
          result = await updateGroupDiscussion(params)
        } else {
          result = await addGroupDiscussion(params)
        }

        ElMessage.success('提交成功')
        emit('handleSubmit', result)
        return result
      })
      .catch(error => {
        console.error('提交失败:', error)
        reject(error)
      })
  })
}

// Watch props.id change
watch(
  () => props.id,
  newVal => {
    if (newVal) {
      getDetail(newVal)
    } else {
      reset()
    }
    handleCaseList()
  },
  { immediate: true }
)

const numberList = ref([])
async function handleCaseList() {
  const res = await getCaseList()
  numberList.value = res.data.map(item => ({
    label: item.caseNo,
    value: item.id,
  }))
}
// Expose methods
defineExpose({
  submitForm,
  handlePreview,
  reset,
  formData,
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
